package com.example.iitematicviewer.util.uploadFile;

import com.alibaba.fastjson.JSONObject;
import com.example.iitematicviewer.constant.Constant;
import com.example.iitematicviewer.constant.ExceptionConstant;
import com.example.iitematicviewer.util.MultipartFileToFile;
import com.example.iitematicviewer.vo.ResultVO;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.io.*;

@Service
public class UploadFileService {

    public ResultVO uploadFile(HttpServletRequest request,ResultVO resultVO)throws IOException {
        try{
            resultVO.setCode(ExceptionConstant.two);
            String fileName = request.getParameter(UploadFileConstant.file_name);
            MultipartHttpServletRequest multipartRequest=(MultipartHttpServletRequest) request;
            MultipartFile multipartFile = multipartRequest.getFile("file");
            assert multipartFile != null;
            String file = MultipartFileToFile.saveMultipartFile(multipartFile, UploadFileConstant.fileDir, fileName);
            if (StringUtils.isNotEmpty(file)) {
                JSONObject obj = new JSONObject();
                obj.put("fileRoute",file);
                obj.put("fileName",fileName);
                resultVO.setData(obj);
                resultVO.setMessage(ExceptionConstant.upload);
            }
            else {
                throw new RuntimeException();
            }
        }catch (Exception e){
            resultVO.setCode(ExceptionConstant.five);
            resultVO.setMessage(ExceptionConstant.badUpload + e.getMessage());
        }
        return resultVO;
    }

}
